package com.wr.utils;

import com.wr.annotation.Autowired;
import com.wr.annotation.Component;

import java.sql.Connection;

/**
 * @author 王瑞
 * @descreption: 获取数据库连接的工具类，本类可以将数据库的connection绑定到当前线程 当当前线程持有一个connection的时候，就直接使用这个conection，而不是每次都新建
 * @date 2020/2/14  23:45
 */

@Component
public class ConnectionUtil {

    @Autowired
    private DataSourceUtil dataSourceUtil;

    public void setDataSourceUtil(DataSourceUtil dataSourceUtil) {
        this.dataSourceUtil = dataSourceUtil;
    }

    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();


    public Connection getConnection() throws Exception{
        Connection connection = threadLocal.get();
        if (connection==null){
            System.out.println("获取数据库连接");
             connection = dataSourceUtil.getDataSource().getConnection();
            threadLocal.set(connection);
        }
        return connection;

    }
}
